﻿using AutoMapper;
using ProjectManageSystemApi.DbEntity;
using ProjectManageSystemApi.Enums;
using ProjectManageSystemApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManageSystemApi.Services.Impl
{
    public class CostTypeServices : ICostTypeServices
    {
        readonly IFreeSql _fsql;
        readonly IMapper _mapper;
        public CostTypeServices(IFreeSql fsql, IMapper mapper) 
        {
            this._fsql = fsql;
            this._mapper = mapper;
        }
        public bool Create(CostTypeDto costType, long userId)
        {
            var data = _mapper.Map<CostType>(costType);
            data.CreateTime = DateTime.Now;
            data.CreateUser = userId;
            data.State = (sbyte)CostTypeState.Exist;
            return _fsql.Insert<CostType>(data).ExecuteAffrows() > 0;
        }

        public bool Update(CostTypeDto costType) 
        {
            var data = _mapper.Map<CostType>(costType);
            return _fsql.Update<CostType>(costType.Id).SetSource(data)
                .IgnoreColumns(x => new { x.CreateTime, x.CreateUser, x.State }).ExecuteAffrows() > 0;
        }

        public bool Delete(int id) 
        {
            return _fsql.Update<CostType>(id).Set(x=> x.State, (int)CostTypeState.Delete).ExecuteAffrows() > 0;
        }

        public bool HasExistId(int id) 
        {
            return _fsql.Select<CostType>().Any(x => x.Id == id && x.State < (int)CostTypeState.Delete);
        }
        public bool HasExistName(string name, int id = 0) 
        {
            return _fsql.Select<CostType>().Any(x => x.Id != id && x.Name == name && x.State < (int)CostTypeState.Delete);
        }
        public PageVo<List<CostTypeDto>> GetAll(PageBo<CostTypeParams> pageBo) 
        {
            var datas = _fsql.Select<CostType>().Where(x => x.State < (int)CostTypeState.Delete)
                .Include(x=> x.UserInfo);
            if (!string.IsNullOrWhiteSpace(pageBo.Param.Name)) 
            {
                datas = datas.Where(x => x.Name.Contains(pageBo.Param.Name));
            }
            long count = datas.Count();
            datas = datas.Page(pageBo.Page, pageBo.Size);

            return new PageVo<List<CostTypeDto>>
            {
                Page = pageBo.Page,
                Size = pageBo.Size,
                Total = count,
                Datas = _mapper.Map<List<CostTypeDto>>(datas.ToList())
            };
        }
    }
}
